<template>
  <basic-container>
    <div style="failureClass">
      <div class="formContainer">
        <div class="formClass">
          <avue-form class="search-form" ref="badConfirmProperties" v-model="badCodeModel" :option="badCodeOption">
            <template slot="productSequenceNumber">
              <el-input
                placeholder="请输入产品序列号"
                v-model="badCodeModel.productSequenceNumber"
                clearable
                @keydown.enter.native="enterProductSequenceNumber(badCodeModel.productSequenceNumber)"
              >
              </el-input>
            </template>
            <template slot="workOrderNo">
              <el-input
                slot="append"
                icon="el-icon-circle-close"
                placeholder="请输入工单号"
                v-model="badCodeModel.workOrderNo"
                clearable
                @keyup.enter.native="findWorkOrderNoByNo(badCodeModel.workOrderNo)"
              >
                <el-button
                  slot="append"
                  icon="el-icon-search"
                  @click="
                    openCommonModal({
                      type: 'workOrder'
                    })
                  "
                ></el-button>
              </el-input>
            </template>
            <template slot="failureCode">
              <el-input
                v-model="badCodeModel.failureCode"
                name="failureCode"
                :clearable="true"
                placeholder="输入不良现象代码"
                suffix-icon="iconfont iconicon_scan"
                @keydown.enter.native="enterFailureCode(badCodeModel.failureCode)"
              >
                <el-button slot="append" icon="el-icon-search" @click="openFailureCommonModal()"></el-button>
              </el-input>
            </template>
            <template slot="failureName">
              <avue-select
                class="failureNameSelect"
                popper-class="el-select_popperClass"
                multiple
                clearable="false"
                v-model="failureNameForm"
                placeholder="不良现象"
                :dic="failureNameDic"
                :props="{
                  label: 'name',
                  value: 'code'
                }"
                @change="handleFailureNameDelete($event)"
                readonly="true"
              ></avue-select>
            </template>
            <template slot="entryBadCode">
              <div class="entry-btn-wrapper">
                <el-button size="small" icon="el-icon-delete" @click="clickClear()">清 空</el-button>
                <el-button type="primary" icon="el-icon-circle-plus-outline" size="small" @click="submitBadCode">提 交</el-button>
              </div>
            </template>
          </avue-form>
        </div>
      </div>
      <avue-crud
        ref="crud"
        :option="option"
        :page.sync="page"
        :table-loading="loading"
        :data="data"
        @current-change="currentChange"
        @size-change="sizeChange"
        @row-del="rowDel"
        @selection-change="selectionChange"
      >
      </avue-crud>
    </div>
    <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"></common-modal-template>
    <global-modal-template :visibile.sync="visibile" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"> </global-modal-template>
  </basic-container>
</template>

<script>
import { submit, getFailureList, getWorkOrderLine, getStation, getProductSn, getWorkOrderRoute, checkCode, remove, getWorkOrderDetail } from '@/api/repair/failurerecord';
import GlobalModalTemplate from '@/components/common-modal-template/global-modal-template.vue';
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';

import { mapGetters } from 'vuex';
import userTableConfig from '@/components/user-table-config';
import userConfig from '@/mixins/userConfig';
export default {
  components: {
    GlobalModalTemplate,
    CommonModalTemplate,
    userTableConfig
  },
  mixins: [userConfig()],
  data() {
    return {
      pageCode: 'FAILURE_RECORD',
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      loading: false,
      badCodeModel: {},
      lineNameList: [],
      stationNameList: [],
      failureNameForm: [],
      failureNameDic: [],
      badCodeOptions: [], // 不良代码列表
      fromRouteOptions: [], // 不良工序列表
      badCodeOption: {
        emptyBtn: false,
        submitBtn: false,
        labelWidth: 120,
        column: [
          {
            label: '工单号',
            prop: 'workOrderNo',
            type: 'search',
            span: 12,
            rules: [
              {
                required: true,
                message: '请输入工单号',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '产品序列号',
            prop: 'productSequenceNumber',
            span: 12
          },
          {
            label: '产品编码',
            prop: 'productPartNo',
            disabled: true,
            span: 12
          },
          {
            label: '产品名称',
            prop: 'productPartName',
            disabled: true,
            span: 12
          },
          {
            label: '产品型号',
            prop: 'productPartModel',
            disabled: true,
            span: 12
          },
          {
            label: '不良数',
            prop: 'quantity',
            type: 'number',
            minRows: 1,
            span: 12,
            disabled: false,
            rules: [
              {
                required: true,
                message: '请输入不良数',
                trigger: 'blur'
              },
              {
                required: true,
                trigger: 'blur',
                validator: (rule, value, callback) => {
                  let reg = /^\+?[1-9]\d*$/;
                  if (!reg.test(value)) {
                    callback(new Error('只能输入正整数'));
                  } else {
                    callback();
                  }
                }
              }
            ]
          },
          {
            label: '登记产线',
            prop: 'lineId',
            type: 'select',
            dicData: [],
            span: 12,
            props: {
              label: 'name',
              value: 'id'
            },
            change: ({ value }) => {
              if (value) {
                this.changeLine(value);
              }
            },
            rules: [
              {
                required: true,
                message: '请选择登记产线',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '登记工序',
            prop: 'fromRouteId',
            type: 'select',
            dicData: [],
            span: 12,
            props: {
              label: 'routeName',
              value: 'id'
            },
            change: ({ value }) => {
              if (value) {
                this.changeFromRouteId(value);
              }
            },
            rules: [
              {
                required: true,
                message: '请选择登记工序',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '登记工段',
            prop: 'sectionName',
            disabled: true
          },
          {
            label: '登记工位',
            prop: 'stationId',
            type: 'select',
            dicData: [],
            span: 12,
            props: {
              label: 'name',
              value: 'id'
            }
          },
          {
            label: '不良现象代码',
            prop: 'failureCode',
            span: 12,
            rules: [
              {
                required: true,
                trigger: 'blur',
                validator: (rule, value, callback) => {
                  if (this.failureNameForm.length <= 0) {
                    callback(new Error('请输入不良代码或者扫描代码'));
                  } else {
                    callback();
                  }
                }
              }
            ]
          },
          {
            label: '不良现象',
            prop: 'failureName',
            type: 'textarea',
            minRows: 2,
            maxRows: 2,
            span: 12
          },
          {
            label: '登记人员',
            prop: 'registryByName',
            type: 'search',
            span: 12,
            disabled: true,
            placeholder: '请选择登记人员',
            appendClick: () => {
              this.openUserInfoCommonModal();
            }
          },
          {
            label: '不良登记说明',
            prop: 'remark',
            type: 'textarea',
            row: true,
            minRows: 2,
            maxRows: 2,
            span: 24
          },
          {
            span: 24,
            label: '',
            display: true,
            prop: 'entryBadCode'
          }
        ]
      },
      selectionList: [],
      data: [],
      visibile: false,
      modalName: '', //打开公用模态框名称
      tableOption: {}, //公用模态框配置信息
      timer: new Date().getTime(), //不同内容使用同一个模态框结构，key值不同需要重新请求渲染数据，否则会请求到上一个使用的数据内容
      option: {
        height: 'calc(100vh - 485px)',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        emptyBtn: false,
        searchBtn: false,
        // searchMenuSpan: 24,
        searchSpan: 24,
        border: true,
        viewBtn: false,
        addBtn: false,
        editBtn: false,
        delBtn: true,
        selection: true,
        menuWidth: 200, //弹框内字段宽度属性
        // searchLabelWidth: '120',
        columnBtn: false,
        index: true,
        indexLabel: '序号',
        column: [
          {
            label: '工单号',
            prop: 'workOrderNo',
            rules: [
              {
                required: true,
                message: '请输入工单号',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '序列号',
            prop: 'productSn',
            rules: [
              {
                required: true,
                message: '请输入序列号',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '产品编码',
            prop: 'productPartNo',
            rules: [
              {
                required: false,
                message: '请输入产品编码',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '产品名称',
            prop: 'productPartName',
            rules: [
              {
                required: false,
                message: '请输入产品名称',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '产品型号',
            prop: 'productPartModel'
          },
          {
            label: '不良数',
            prop: 'badQuantity'
          },
          {
            label: '登记产线',
            prop: 'lineName'
          },
          {
            label: '登记工序',
            prop: 'routeName'
          },
          {
            label: '登记工位',
            prop: 'stationName'
          },
          {
            label: '不良现象',
            prop: 'badPhenomenonName'
          },
          {
            label: '登记说明',
            prop: 'registerDescription'
          },
          {
            label: '登记时间',
            prop: 'registerTime'
          },
          {
            label: '已维修次数',
            prop: 'repairTimes'
          }
        ]
      }
    };
  },
  mounted() {
    this.$nextTick(() => {
      let userObj = JSON.parse(localStorage.getItem('saber-userInfo')) || {
        content: {
          user_id: '',
          real_name: ''
        }
      };
      this.badCodeModel.registryBy = userObj.content.user_id;
      this.badCodeModel.registryByName = userObj.content.real_name;
    });
  },
  computed: {
    ...mapGetters(['permission'])
  },
  watch: {
    'badCodeModel.productSequenceNumber'(value) {
      let quantity = this.findObject(this.badCodeOption.column, 'quantity');
      if (value) {
        quantity.disabled = true;
        this.badCodeModel.quantity = 1;
      } else {
        quantity.disabled = false;
      }
    }
  },
  methods: {
    changeFromRouteId(fromRouteId) {
      let findIndex = this.fromRouteOptions.findIndex((route) => route.id == fromRouteId);
      if (findIndex > -1) {
        this.badCodeModel.sectionName = this.fromRouteOptions[findIndex].workSectionName;
        this.badCodeModel.sectionId = this.fromRouteOptions[findIndex].workSectionId;
      }
    },
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.getFailureData(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
      this.getFailureData(this.page);
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
      this.getFailureData(this.page);
    },
    /**
     * 获取不良登记数据
     * */
    getFailureData(page, params = {}) {
      this.loading = true;
      getFailureList(page.currentPage, page.pageSize, {
        workOrderId: this.badCodeModel.workOrderId
      }).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
      });
    },
    /**
     * 工单回车
     * */
    findWorkOrderNoByNo(workOrderNo) {
      // this.badCodeModel.fromRouteCode = '';
      // this.badCodeModel.fromRouteId = '';
      // this.badCodeModel.fromRouteName = '';
      // this.fromRouteOptions = [];
      if (!workOrderNo) {
        this.$message.warning('请输入工单号！');
        return;
      }
      getWorkOrderDetail(workOrderNo).then((res) => {
        let data = res.data.data;
        this.badCodeModel.workOrderId = this._get(data, 'id', '');
        this.badCodeModel.productPartNo = this._get(data, 'productPartNo', '');
        this.badCodeModel.productPartName = this._get(data, 'productPartName', '');
        this.badCodeModel.productPartModel = this._get(data, 'productPartModel', '');
        this.badCodeModel.productPartId = this._get(data, 'productPartId', '');
        this.findLineList(this.badCodeModel.workOrderId);
        this.findWorkOrderRoute(this.badCodeModel.workOrderId);
        this.getFailureData(this.page);
      });
    },
    /***
     * 序列号回车
     * */
    enterProductSequenceNumber(productSequenceNumber) {
      if (!productSequenceNumber) {
        this.$message.warning('请输入产品序列号！');
        return;
      }
      getProductSn({
        sequenceNumber: productSequenceNumber
      }).then(
        (res) => {
          let data = res.data.data || {};
          if (this.badCodeModel.workOrderNo && this.badCodeModel.workOrderId !== data.workOrderId) {
            this.$message.warning('该产品序列号不属于该工单，请检查后再操作！');
            this.badCodeModel.productSequenceNumber = '';
          } else {
            this.badCodeModel = data;
            this.badCodeModel.productId = data.id;
            this.badCodeModel.productSequenceNumber = productSequenceNumber;
            this.badCodeModel.fromRouteId = data.routeId;
            this.$message.success(res.data.msg);
            this.findLineList(this.badCodeModel.workOrderId);
            this.findWorkOrderRoute(this.badCodeModel.workOrderId);
            this.getFailureData(this.page);
          }
        },
        (error) => {
          console.log(error);
        }
      );
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    /**
     * 不良现象删除
     * */
    handleFailureNameDelete(items) {
      this.failureNameDic = this.failureNameDic.filter((item) => {
        if (items.includes(item.code)) {
          return item;
        }
      });
    },
    /**
     * 扫描不良现象代码
     * */
    enterFailureCode(code) {
      if (!code) {
        this.$message({
          type: 'warning',
          message: '不良现象代码不能为空!'
        });
        return;
      }
      checkCode({
        code
      })
        .then((res) => {
          let data = res.data.data;
          this.failureNameDic = this._uniqWith([...this.failureNameDic, ...[data]], (arrVal, othVal) => {
            return arrVal.id === othVal.id;
          });
          this.failureNameForm = this.failureNameDic.map((item) => item.code);
          this.$message({
            type: 'success',
            message: res.data.msg
          });
        })
        .catch((err) => {
          this.badCodeModel.code = '';
        });
    },
    /**
     * 提交不良登记
     * */
    async submitBadCode() {
      this.$refs.badConfirmProperties.validate((valid, done) => {
        if (valid) {
          let lineObj = this.lineNameList.find((item) => item.id === this.badCodeModel.lineId) || {};
          let routeObj = this.fromRouteOptions.find((item) => item.id === this.badCodeModel.fromRouteId) || {};
          let stationObj = this.stationNameList.find((item) => item.id === this.badCodeModel.stationId) || {};
          this.badCodeModel.lineName = lineObj.name;
          this.badCodeModel.workshopId = lineObj.workshopId;
          this.badCodeModel.workshopName = lineObj.workshopName;

          this.badCodeModel.routeId = routeObj.id;
          this.badCodeModel.routeName = routeObj.routeName;

          this.badCodeModel.stationName = stationObj.name;

          let repaireRegisterDetailDTOList = this.failureNameDic.map((item) => {
            return {
              badPhenomenonId: item.id,
              badPhenomenonCode: item.code,
              badPhenomenonName: item.name
            };
          });
          let params = {
            ...this.badCodeModel,
            productSn: this.badCodeModel.productSequenceNumber,
            inputSource: 'MANUAL',
            badQuantity: this.badCodeModel.quantity,
            registerUserName: this.badCodeModel.registryByName,
            registerUserId: this.badCodeModel.registryBy,
            registerDescription: this.badCodeModel.remark,
            repaireRegisterDetailDTOList
          };
          delete params.id;
          submit(params).then((res) => {
            this.handleClear();
            this.$message({
              type: 'success',
              message: '操作成功!'
            });
          });
        }
        done();
      });
    },
    /**
     * 清空
     * */
    handleClear() {
      let workOrderNo = this.badCodeModel.workOrderNo;
      let workOrderId = this.badCodeModel.workOrderId;
      let registryBy = this.badCodeModel.registryBy;
      let registryByName = this.badCodeModel.registryByName;
      this.badCodeModel = {};
      this.lineNameList = [];
      this.fromRouteOptions = [];
      this.stationNameList = [];
      this.failureNameDic = [];
      this.failureNameForm = [];
      this.data = [];
      this.$refs.badConfirmProperties.resetFields();
      setTimeout(() => {
        this.$set(this.badCodeModel, 'workOrderNo', workOrderNo);
        this.badCodeModel.workOrderId = workOrderId;
        this.badCodeModel.registryBy = registryBy;
        this.badCodeModel.registryByName = registryByName;
        this.getFailureData(this.page);
      });
    },
    clickClear() {
      this.badCodeModel = {};
      this.lineNameList = [];
      this.fromRouteOptions = [];
      this.stationNameList = [];
      this.failureNameDic = [];
      this.failureNameForm = [];
      this.data = [];
      this.$refs.badConfirmProperties.resetFields();
    },
    /**
     * 不良登记工序选择
     * */
    changeFromRoute(value) {
      if (value) {
        let findIndex = this.fromRouteOptions.findIndex((route) => route.fromRouteId == value);
        if (findIndex > -1) {
          this.badCodeModel.fromRouteCode = this.fromRouteOptions[findIndex].fromRouteCode;
          this.badCodeModel.fromRouteId = this.fromRouteOptions[findIndex].fromRouteId;
          this.badCodeModel.fromRouteName = this.fromRouteOptions[findIndex].fromRouteName;
        }
      }
    },

    /**
     * 获取选择的物料模态框行数据
     * */
    getSelectedRows(rowData) {
      switch (this.modalName) {
        case 'workOrderModal':
          this.visibile = false;
          this.$set(this.badCodeModel, 'workOrderNo', this._get(rowData, 'workOrderNo', ''));
          this.findWorkOrderNoByNo(this.badCodeModel.workOrderNo);
          break;
        case 'failureCode':
          this.failureNameDic = this._uniqWith([...this.failureNameDic, ...rowData], (arrVal, othVal) => {
            return arrVal.id === othVal.id;
          });
          this.failureNameForm = this.failureNameDic.map((item) => item.code);
          break;
        case 'registryByName':
          this.badCodeModel.registryBy = this._get(rowData, 'id', '');
          this.badCodeModel.registryByName = this._get(rowData, 'realName', '');
          break;
        default:
          break;
      }
    },
    // 根据工单id获取工序
    findWorkOrderRoute(workorderId) {
      getWorkOrderRoute({ workorderId }).then((res) => {
        let data = res.data.data || [];
        this.fromRouteOptions = data;
        let fromRouteId = this.findObject(this.badCodeOption.column, 'fromRouteId');
        fromRouteId.dicData = data;
      });
    },
    //根据工单获取产线
    findLineList(workOrderId) {
      getWorkOrderLine({
        workOrderId
      }).then((res) => {
        let data = res.data.data || [];
        this.lineNameList = data;
        let lineId = this.findObject(this.badCodeOption.column, 'lineId');
        lineId.dicData = data;
        if (this.badCodeModel.lineId) {
          this.findStationList(lineId);
        }
      });
    },
    /**
     * 产线选择
     * */
    changeLine(lineId) {
      this.findStationList(lineId);
    },
    //获取产线工位列表
    findStationList(lineId) {
      getStation(lineId).then((res) => {
        let data = res.data.data;
        this.stationNameList = data || [];
        let stationId = this.findObject(this.badCodeOption.column, 'stationId');
        stationId.dicData = data;
      });
    },
    /*
     * 不良代码选择框
     */
    openFailureCommonModal() {
      this.$refs.commonModalTemplate.showModal();
      this.modalName = 'failureCode';
      this.tableOption = {
        modalTitle: '选择不良现象代码信息（双击进行选择）',
        url: '/api/mes-product/mro-dict/page?dictType=BAD_PHENOMENON',
        isPage: true,
        index: false,
        searchBtn: true,
        rowSelectionType: 'mutiple',
        searchLabelWidth: 100,
        columnDefs: [
          {
            label: '不良现象代码',
            prop: 'code',
            search: true,
            row: true,
            span: 24,
            rules: [
              {
                required: true,
                message: '请输入不良代码',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '不良现象',
            prop: 'name',
            search: true,
            row: true,
            span: 24,
            rules: [
              {
                required: true,
                message: '请输入不良现象描述',
                trigger: 'blur'
              }
            ]
          }
        ]
      };
    },
    openCommonModal(params) {
      let { type } = params;
      switch (type) {
        case 'workOrder':
          this.modalName = 'workOrderModal';
          this.visibile = true;
          this.tableOption = {
            modalTitle: '选择工单信息（双击进行选择）',
            url: '/api/mes-product/work-order/page',
            isPage: true,
            rowSelectionType: 'single',
            menu: false,
            editBtn: false,
            menuWidth: 100,
            searchLabelWidth: 90,
            templateName: 'WORKORDER'
          };
          break;
        default:
          break;
      }
    },
    // 重新加载公用表格弹窗组件
    newKey() {
      this.timer = new Date().getTime();
    },
    /**
     * 打开用户选择模态框
     */
    openUserInfoCommonModal() {
      this.modalName = 'registryByName';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择不良登记人员信息（双击进行选择）',
        url: '/api/blade-system/user/page',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '用户姓名',
            prop: 'realName',
            search: true,
            searchLabelWidth: 150,
            searchSpan: 8
          },
          {
            label: '所属部门',
            prop: 'deptName',
            searchLabelWidth: 150,
            searchSpan: 8
          },
          {
            label: '职务',
            prop: 'postName'
          },
          {
            label: '用户平台',
            prop: 'userTypeName'
          }
        ]
      };
    }
  }
};
</script>

<style scoped>
.failureClass {
  width: 100%;
  display: flex;
  flex-direction: column;
}

.formContainer {
  display: flex;
  justify-content: center;
  width: 90%;
}

.formClass {
  width: 60%;
}

::v-deep .search-form .entry-btn-wrapper {
  width: 100%;
  display: flex;
  justify-content: flex-end;
}
.footer {
  display: flex;
  justify-content: flex-end;
  margin: 20px 0;
}
::v-deep .avue-crud .avue-crud__menu {
  display: none !important;
}

::v-deep .failureNameSelect .el-input__suffix {
  display: none;
}
/** ::v-deep .avue-select input {
  min-height: 58px !important;
}
*/
</style>
